package com.base.controller;


import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.base.entity.User;
import com.base.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 作者
 * @since 2024-06-11
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @PostMapping("/login")
    public SaResult login(User user) {
        User foundUser = userService.getOne(new QueryWrapper<User>()
                .eq("username", user.getUsername()));
        if (foundUser == null) {
            return SaResult.error("账号不存在！");
        }
        if (foundUser.getPassword().equals(user.getPassword())) {
            StpUtil.login(foundUser.getId());
            StpUtil.getSession().set("role", foundUser.getRole());
            return SaResult.ok();
        } else {
            return SaResult.error("密码错误！");
        }
    }

//    新增
    @PostMapping("/register")
    public SaResult register(User user) {
        try {
            userService.save(user);
            return SaResult.ok();
        }catch (Exception e){
            return SaResult.error("用户名被占用");
        }

    }

//    删除
    @GetMapping("/remove/{id}")
    public SaResult remove(@PathVariable("id") Integer id) {
        userService.removeById(id);
        return SaResult.ok();
    }

//    修改
    @PostMapping("/update")
    public SaResult update(User user) {
        userService.updateById(user);
        return SaResult.ok();
    }

//    获取某个
    @GetMapping("/get/{id}")
    public SaResult get(@PathVariable("id") Integer id) {
        User user = userService.getById(id);
        return SaResult.data(user);
    }





}
